#coding:utf-8
__author__ = 'nhsheng'

import pymysql
import readConfig
from common.Log import logger
from DBUtils.PooledDB import PooledDB

'''数据库相关操作'''

DATABASE=readConfig.ReadConfig().get_section('DATABASE')

host=DATABASE.get('host')
username=DATABASE.get('username')
password=DATABASE.get('password')

class MYSQL:

    '''初始化数据库'''
    def __init__(self,database=None):
        self.database=database
        try:
            pool = PooledDB(pymysql,10,host=host,user=username,password=password,charset='utf8',cursorclass=pymysql.cursors.DictCursor)
            self.conn = pool.connection()
        except Exception as e:
            logger().error('%s 数据库连接失败！',self.database)

    '''查询一条数据'''
    def execQueryOne(self,sql):
        try:
            logger().info('执行sql语句:%s',sql)
            cur=self.conn.cursor()
            cur.execute(sql)
            list=cur.fetchone()
            self.conn.commit()
            cur.close()
            logger().info('sql执行结果：%s',list)
            return list
        except Exception as e:
            logger().error('sql语句执行失败，错误原因为%s',e)

    '''查询多条数据'''
    def execQueryAll(self,sql):
        try:
            logger().info('执行sql语句:%s',sql)
            cur=self.conn.cursor()
            cur.execute(sql)
            list=cur.fetchall()
            self.conn.commit()
            cur.close()
            logger().info('sql执行结果：%s',list)
            return list
        except Exception as e:
            logger().error('sql语句执行失败，错误原因为%s',e)

    '''插入，更新，删除操作'''
    def execNonQuery(self,sql):
        try:
            logger().info('执行sql语句:%s',sql)
            cur=self.conn.cursor()
            cur.execute(sql)
            self.conn.commit()
            cur.close()
            logger().info('sql执行结果：%s',list)
        except Exception as e:
            logger().error('sql语句执行失败，错误原因为%s',e)

